package com.panshi.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro内置过滤器
        /**
         * //redirect
         * anon:无需认证可以访问
         * authc：必须认证才能访问
         *user：必须拥有 记住我 功能才能用
         * perms：拥有对某个资源的权限才能访问
         * role 拥有某个角色才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap();

        //授权 user用户需要有add权限
        filterMap.put("/user/list","perms[user:list]");
        filterMap.put("/user/upd","perms[user:upd]");
        filterMap.put("/user/del","perms[user:del]");
        //filterMap.put("/user/add","anon");
        //登录拦截
        filterMap.put("/user/*","authc");
        filterMap.put("/*","authc");
        filterMap.put("/login","anon");
        bean.setFilterChainDefinitionMap(filterMap);

        //无权限跳转到登录页面
        bean.setLoginUrl("/login");

        //设置未授权请求
        bean.setUnauthorizedUrl("/noauth");


        return bean;
    }


    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //连接userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象 需要自定义

    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }


    //整合shirodialect
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}
